/**
 * 链表结构 - start
 */

class Node {
  constructor(value) {
    this.val = value;
    this.next = null;
  }
}

class LinkedList {
  constructor() {
    this.head = null;
  }
  append(value) {
    let newNode = new Node(value);
    if (!this.head) {
      this.head = newNode;
    } else {
      let current = this.head;
      while (current.next) {
        current = current.next;
      }
      current.next = newNode;
    }
  }
}

/**
 * 链表结构 - end
 */

// 测试用例 - demo - [1,2,3];
let demo = new LinkedList();
demo.append(1);
demo.append(2);
demo.append(3);
demo.append(4);

// ----------------------------------------------
// ----------------------------------------------
// ----------------------------------------------
// ----------------------------------------------
// 输入一个链表，按链表从尾到头的顺序返回一个 ArrayList。
const printListFromTailToHead = (head) => {
  let res = [];
  while (head) {
    // 从res的头部把链表内容推入
    // 这样链表前面的元素就会存在res的后面
    res.unshift(head.val);
    head = head.next;
  }
  return res;
};

console.log(printListFromTailToHead(demo.head));
